<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2021/3/8
 * Time: 12:05 下午
 */

namespace app\common\service;

use app\common\cachemodel\acquired_astro\AppAcquiredAstroTestRecord;
use app\common\cachemodel\ai_chat_room\AiChatUserDuration;
use app\common\cachemodel\ai_chat_room\AiChatUserDurationChangeRecord;
use app\common\cachemodel\AppConfig;
use app\common\cachemodel\Goods;
use app\common\cachemodel\live\LiveAnswerAstroRecord;
use app\common\cachemodel\live\LiveAnswerDiceRecord;
use app\common\cachemodel\live\LiveAnswerTarotRecord;
use app\common\cachemodel\live\LiveOrderData;
use app\common\cachemodel\lucky\AppLuckyTaskRecord;
use app\common\cachemodel\MallGoods;
use app\common\cachemodel\name_analyze\Zl9NameAnalyzeCreateNameRecord;
use app\common\cachemodel\name_analyze\Zl9NameAnalyzeRecord;
use app\common\cachemodel\NatalReport;
use app\common\cachemodel\Orders as OrdersCacheModel;
use app\common\cachemodel\OrdersLib as OrdersLibCacheModel;
use app\common\cachemodel\privatearea\PrivateAreaGoods;
use app\common\cachemodel\privatearea\PrivateAreaMallGoodsAttr;
use app\common\cachemodel\privatearea\PrivateAreaOrders;
use app\common\cachemodel\privatearea\PrivateAreaQuestionInfo;
use app\common\cachemodel\Recode;
use app\common\cachemodel\Rectification;
use app\common\cachemodel\RectificationEvent;
use app\common\cachemodel\UserCoupon;
use app\common\cachemodel\ZhunleUserAccountRecord;
use app\common\cachemodel\zl1_relation\Zl1IdeaTag;
use app\common\cachemodel\zl1_relation\Zl1RelationAnalysisFitYou;
use app\common\cachemodel\zl1_relation\Zl1RelationAnalysisIdea;
use app\common\cachemodel\zl1_relation\Zl1RelationAnalysisReport;
use app\common\cachemodel\zl3\Zl3FortuneYear2022Active;
use app\common\cachemodel\zl3\Zl3FortuneYearAnalysis;
use app\common\cachemodel\zl4\Zl4HoroscopeGoodTime;
use app\common\cachemodel\zl4\Zl4HoroscopeGoodTimeTemp;
use app\common\cachemodel\zl4\Zl4HoroscopeReport;
use app\common\cachemodel\zl6\Zl6MeditationUnlockData;
use app\common\cachemodel\zl7\Zl7AiAnswerNumData;
use app\common\cachemodel\zlcr2\Zlcr2UserQuestion;
use app\common\cachemodel\ZlcrCustomReportQuestion;
use app\common\cachemodel\ZlSynastryReport;
use app\common\cachemodel\ZlTarotRecords;
use app\common\lib\PushQueue;
use app\common\lib\SensorsData;
use app\common\lib\Util;
use Exception;
use think\Db;
use think\Env;
use think\Log;

/**
 * Class Orders
 */
class Orders
{
    protected $nowTime;

    public function __construct()
    {
        $this->nowTime = time();
    }

    /**
     * 回调后的逻辑处理
     * @param $order_id
     * @param $total_amount
     * @param int $trade_type 支付方式   1=>支付宝,2=>微信支付，3=>余额，4=>准币，5=>京东，6=>微信JSAPI，7=>支付宝手机网页，8=>微信H5，9=>苹果支付，13=>微信小程序支付,14=>广告解锁，15=>微信浏览器打开H5页面使用JSAPI支付
     * @return bool
     */
    public function notify_handle($order_id, $total_amount, $trade_type = 0, $transactionId = ''): bool
    {
        Db::startTrans();
        try
        {
            $num = $this->check_type($order_id);
            if ($num === 7)//准币
            {
                $order = (new ZhunleUserAccountRecord())->where('order_id', $order_id)->field('uid,status')->find();
                if (!$order || $order['status'])
                {
                    return true;
                }
                $startTransStatus = $this->UpdateCoin($order_id, $total_amount, $order['uid'], $trade_type);
            } elseif ($num === 8)//商城
            {
                $ordersInfo = $this->GetOrdersGoodsInfo($order_id);
                $order = current($ordersInfo);
                if ($order['status'])
                {
                    return true;
                }
                (new Recode())->UpdateData($order['uid'], $order['rid'], [], 1);
                //增加直播间数据统计记录
                (new LiveOrderData())->saveData($ordersInfo);
                $startTransStatus = $this->UpdateMall($order, $trade_type);
            } elseif (in_array($num, [51, 52, 53, 54, 55, 56], true))//私域
            {
                $startTransStatus = $this->UpdatePrivateAreaOrder($order_id, $total_amount);
            } elseif ($num === 57)
            {   // 私域实物商城
                $startTransStatus = $this->UpdatePrivateAreaMallOrder($order_id, $total_amount, $trade_type);
            } else//虚拟商品
            {
                $ordersInfo = $this->GetOrdersGoodsInfo($order_id);
                $order = current($ordersInfo);
                (new Recode())->UpdateData($order['uid'], $order['rid'], [], 1);
                //增加直播间数据统计记录
                (new LiveOrderData())->saveData($ordersInfo);
                $startTransStatus = $this->UpdateOrder($num, $ordersInfo, $total_amount, $order_id, $trade_type, $transactionId);
            }
            Db::commit();
        }
        catch (\Exception $e)
        {
            $startTransStatus = false;
            Log::write('支付回调失败：[' . $order_id . '] ' . $e->getMessage() . '【' . $e->getFile() . $e->getLine() . '】', 'error', true);
            Db::rollback();
        }
        return $startTransStatus;
    }

    /**
     * 更新商城订单
     * @param $ordersInfo
     * @param $trade_type
     * @return bool
     * @throws Exception
     */
    private function UpdateMall($ordersInfo, $trade_type)
    {
        $nowTime = time();
        //更新2.0订单缓存
        if ($trade_type)
        {
            $data = ['status' => 1, 'pay_time' => $nowTime, 'trade_type' => $trade_type];
        } else
        {
            $data = ['status' => 1, 'pay_time' => $nowTime];
        }
        $mall = json_decode($ordersInfo['extend'], true)['mall'];
        //万幸活动
        $appConfig = (new AppConfig())->configInfo('fortune_year_2022_active');
        if (isset($appConfig[$ordersInfo['gid']]))
        {
            //赠送优惠券
            (new UserCoupon())->systemCouponGive($ordersInfo['uid'], $appConfig[$ordersInfo['gid']], $mall['num'], $ordersInfo['order_id']);
            //订单赠送优惠券日志
            (new Zl3FortuneYear2022Active())->insert(
                [
                    'uid' => $ordersInfo['uid'],
                    'order_num' => $ordersInfo['order_id'],
                    'gid' => $ordersInfo['gid'],
                    'cid' => $appConfig[$ordersInfo['gid']],
                    'create_time' => $nowTime,
                ]
            );
        }
        return (new OrdersCacheModel())->UpdateData($ordersInfo['order_id'], $data, 1);
    }

    /**
     * 更新准币订单数量和状态
     * @param $order_id
     * @param $total_amount
     * @param $uid
     * @param $trade_type
     * @return bool
     */
    private function UpdateCoin($order_id, $total_amount, $uid, $trade_type)
    {
        return OrdersLibCacheModel::UpdateCoin($order_id, 10, $total_amount, $uid, 1, $trade_type);
    }

    /**
     * 更新订单状态
     * @param $num
     * @param $ordersInfo
     * @param $total_amount
     * @param $order_id
     * @param $trade_type
     * @return bool
     * @throws \think\Exception
     */
    private function UpdateOrder($num, $ordersInfo, $total_amount, $order_id, $trade_type, $transactionId = '')
    {
        $nowTime = time();
        $OrdersModel = new \app\common\model\Orders();
        $OrdersCacheModel = new OrdersCacheModel();
        $unlock_gids = array_column($ordersInfo, 'gids');
        $orders = current($ordersInfo);
        $orders['gid'] = (int)$orders['gid'];
        $OrderType = (int)$orders['order_type'];
        if (abs($orders['total_amount'] - $total_amount) > 1)
        {
            Log::write('订单付款金额有疑：订单金额【' . $orders['total_amount'] . '】,回调金额【' . $total_amount . '】');
            return false;
        }
        // 判断订单状态是否已经更新处理过了
        if ($orders['status'])
        {   // 订单已经处理过了 防止重复处理
            return true;
        }
        //订单状态
        if ($OrderType === 22)
        {
            $unlock_gids = [$orders['gid']];
        }
        $status = OrdersLibCacheModel::getOrderStatus($unlock_gids, $OrderType);
        $unlock_gid = current($unlock_gids);
        if (!$unlock_gid)
        {
            $unlock_gid = current($ordersInfo)['gid'];
            $unlock_gids = [];
            $unlock_gids[] = $unlock_gid;
        }

        $extend = json_decode($orders['extend'], true);
        //2.8.5以后幸运星完成其他任务
        $orderVersion = isset($extend['app_info']) ? $extend['app_info']['version'] : '';
        if ($orderVersion)
        {
            if (Util::CheckAppVersion('2.8.5', $orderVersion) !== '小')
            {
                //其他任务完成
                $taskInfo = config('lucky_task.order_task');
                if (isset($taskInfo[$orders['order_type']]) && $unlock_gid != 83)
                {
                    (new AppLuckyTaskRecord())->setOtherTaskSuccess($orders['uid'], $taskInfo[$orders['order_type']], $order_id);
                }
            }
        }
        $answerModel = null;
        // 订单号 如：011806192149570386   01=>生时校正 02=>运势 03=>占星地图，04=>占星视频，05=>本命预测,06=>vip
        switch ($num)
        {
            case  1:// 修改校准生辰状态及入队
                $this->rec($orders, $order_id);
                break;
            case  2://运势
                $this->FortuneQueue($orders);
                break;
            case  3://地图
                $this->MapQueue($orders);
                break;
            case  5://本命报告
                $queueDelay = in_array($orders['env_type'], [2, 7], false) ? 0 : null;
                $this->NatalQueue($orders, $unlock_gids, $order_id, $queueDelay);
                break;
            case 6: //vip更新状态和星力值
                $this->Vip($orders, $orders['gid']);
                break;
            case  9: //定制报告
                $this->customReport($orders);
                break;
            case 10 : //修改塔罗记录状态
                $taroId = $extend['history']['id'];
                (new ZlTarotRecords())->updateData($taroId, ['status' => 1]);
                break;
            case  11://合盘报告
                $queueDelay = in_array($orders['env_type'], [2, 7], false) ? 0 : null;
                $this->SynastryQueue($orders, (int)$unlock_gid, $queueDelay);
                break;
            case  12:
                //更新看盘解答状态
                $answerModel = new LiveAnswerAstroRecord();
                break;
            case  13:
                //更新骰子解答状态
                $answerModel = new LiveAnswerDiceRecord();
                break;
            case  14:
                //更新塔罗解答状态
                $answerModel = new LiveAnswerTarotRecord();
                break;
            case 15://问答
                (new Zlcr2UserQuestion())->orderQuestion(2, $orders['order_id']);
                break;
            case  16://适合你的TA
                //打包解锁特殊处理
                if ($orders['gid'] === 87)
                {
                    $unlock_gids = [84, 85, 86];
                }
                (new Zl1RelationAnalysisFitYou())->SaveAndQueue((int)$orders['uid'], (int)$orders['rid'], $unlock_gids, $order_id);
                break;
            case  17://你的理想型
                $case = $extend['relation_idea_info'];
                (new Zl1RelationAnalysisIdea())->SaveDataAndQueue(['uid' => $orders['uid'], 'rids' => $case['rids'], 'tag_info' => $case['tag_info'], 'gid' => $orders['gid'], 'order_num' => $orders['order_id'], 'create_time' => $this->nowTime]);
                break;
            case  18://怎么追求TA
                $rids = $extend['recode_ids'];
                (new Zl1RelationAnalysisReport())->SaveAndQueue($orders['uid'], 1, $orders['gid'], $order_id, $rids['rid1'], $rids['rid2']);
                break;
            case  19://鉴”渣“神器
                (new Zl1RelationAnalysisReport())->SaveAndQueue($orders['uid'], 2, $orders['gid'], $order_id, $orders['rid']);
                break;
            case  21://年运拓展
                $recodeInfo = $extend['recode_info'];
                if ($orders['gid'] === 91)
                {
                    //获取人生阶段
                    $insertType = 2;
                    $stateYear = Util::getRecodeStageyear($recodeInfo, $extend['year_life']['start_time']);
                    $stageyear = (int)($stateYear['start_year'] . $stateYear['end_year']);
                    $stage_num = $stateYear['num'];

                } elseif ($orders['gid'] === 92)
                {
                    $insertType = 3;
                }
                $inserData = [
                    'uid' => $orders['uid'],
                    'rid' => $recodeInfo['id'],
                    'type' => $insertType ?? 0,
                    'hash' => Util::getRecodeHashKey($recodeInfo),
                    'status' => 1,
                    'order_num' => $orders['order_id'],
                    'stageyear' => $stageyear ?? 0,
                    'stage_num' => $stage_num ?? 0,
                    'recode_info' => json_encode($recodeInfo, JSON_UNESCAPED_UNICODE),
                ];
                (new Zl3FortuneYearAnalysis())->SaveDataAndQueue($inserData);
                break;
            case  22://八字
                $recodeInfo = (new Recode())->getInfoById($orders['rid']);
                $recodeEncode = json_encode($recodeInfo, JSON_UNESCAPED_UNICODE);
                if (Goods::isBaziJsjr(28, $orders['gid']))//择时
                {
                    $GoodTimeSimData = (new Zl4HoroscopeGoodTimeTemp())->getInfoById($extend['history']['id']);
                    $data = [
                        'uid' => $orders['uid'],
                        'hash' => $GoodTimeSimData['hash'],
                        'rid1' => $GoodTimeSimData['rid1'],
                        'rid2' => $GoodTimeSimData['rid2'],
                        'tid' => $GoodTimeSimData['tid'],
                        'status' => 2,  // 直接计算成功
                        'order_num' => $order_id,
                        'start_date' => $GoodTimeSimData['start_date'],
                        'end_date' => $GoodTimeSimData['end_date'],
                        'day_num' => $GoodTimeSimData['day_num'],
                        'unlock_day_num' => $GoodTimeSimData['unlock_day_num'],
                        'unlock_days' => json_encode($GoodTimeSimData['unlock_days'], JSON_UNESCAPED_UNICODE),
                        'content' => json_encode($GoodTimeSimData['content'], JSON_UNESCAPED_UNICODE),
                        'recode_info' => json_encode($GoodTimeSimData['recode_info'], JSON_UNESCAPED_UNICODE),
                        'create_time' => $nowTime,
                        'end_time' => $nowTime,
                    ];
                    (new Zl4HoroscopeGoodTime())->SaveData($orders['uid'], $data);
                } else
                {
                    if ($orders['gid'] === 106)//用神
                    {
                        $type = 2;
                        $statusTmp = 0;
                    } else if ($orders['gid'] === 107)//72格局
                    {
                        $type = 1;
                        $statusTmp = 1;
                    }
                    $data = [
                        'uid' => $orders['uid'],
                        'rid' => $orders['rid'],
                        'type' => $type,    // 类型  1=>72格局判定 2=>用神详解
                        'hash' => Util::getRecodeHashKey($recodeInfo),    //  Util::getRecodeHashKey($recode) 调用该方法获取
                        'status' => $statusTmp,   // 计算状态  0=>待计算 1=>计算中 2=>计算完成 3=>计算失败      72格局判定 默认入库计算中状态 ｜ 用神详解 默认入库 待计算状态
                        'order_num' => $orders['order_id'],   // 订单编号
                        'recode_info' => $recodeEncode,  // 档案信息  json_encode
                    ];
                    (new Zl4HoroscopeReport())->SaveDataAndQueue($data);
                }
                break;
            case 23://冥想
                $meditation = $extend['meditation'];
                $mid = array_keys($meditation)[0];
                (new Zl6MeditationUnlockData())->SaveData($orders['uid'], [
                    'uid' => $orders['uid'],
                    'mid' => $mid,
                    'sign' => $meditation[$mid]['in_sign'],
                    'order_num' => $orders['order_id'],
                    'create_time' => $nowTime,
                ]);
                break;
            case 25://AI解答(骰子塔罗)
            case 26://AI解答
                $num = $extend['ai_answer']['num'];
                (new Zl7AiAnswerNumData())->updateData($orders['uid'], ['ai_num' => ['inc', $num], 'total_num' => ['inc', $num], 'update_time' => $nowTime]);
                break;
            case 29://后天星座
                $acquiredAstroId = (new AppAcquiredAstroTestRecord())->saveData([
                    'uid' => $orders['uid'],
                    'type' => 2,
                    'status' => 0,
                    'order_num' => $orders['order_id'],
                    'create_time' => time(),
                ]);
                $extend['acquired_astro']['id'] = $acquiredAstroId;
                break;
            case 31://疗愈室充电时长
                preg_match('/\d+/', $extend['ai_answer']['duration'], $matches);
                $number = $matches[0] * 60; // 数字为 $matches[0]
                $aiChatUserDurationModel = new AiChatUserDuration();
                $userDration = $aiChatUserDurationModel->getChatUserDurationData($orders['uid']);
                $duration = $userDration['duration'] + $number;
                $totalDuration = $userDration['total_duration'] + $number;
                $aiChatUserDurationModel->UpdateData($orders['uid'], [
                    'duration' => $duration,
                    'total_duration' => $totalDuration,
                    'update_time' => $nowTime
                ]);
                (new AiChatUserDurationChangeRecord())->SaveData([
                    'uid' => $orders['uid'],
                    'type' => 1,
                    'gid' => $orders['gid'],
                    'order_id' => $orders['order_id'],
                    'change_duration' => $number,
                    'res_duration' => $duration,
                    'create_time' => $nowTime,
                ]);
                break;
            case 32://起名/评分
                $historyId = $extend['history']['id'];
                if ($orders['gid'] === 164)
                {
                    //1=>支付宝APP,2=>微信APP支付，4=>准币
                    switch ($trade_type)
                    {
                        case 1:
                            $unlockType = 3;
                            break;
                        case 2:
                            $unlockType = 2;
                            break;
                        case 4:
                            $unlockType = 4;
                            break;
                        default:
                            $unlockType = 0;
                            break;
                    }
                    (new Zl9NameAnalyzeRecord())->payUnlockData($historyId, $unlockType, $order_id);
                } else
                {
                    switch ($trade_type)
                    {
                        case 1:
                            $unlockType = 2;
                            break;
                        case 2:
                            $unlockType = 1;
                            break;
                        case 4:
                            $unlockType = 3;
                            break;
                        default:
                            $unlockType = 0;
                            break;
                    }
                    (new Zl9NameAnalyzeCreateNameRecord())->unlockData($historyId, $unlockType, $order_id);
                }
                break;
        }
        if (isset($answerModel))
        {
            $extend = json_decode($orders['extend'], true);
            $liveInfo = $extend['live_info'];
            $answerModel->updateAnswerRequest(['status' => 2, 'live_id' => $liveInfo['live_id'], 'live_record_id' => $liveInfo['live_record_id'], 'uid' => $orders['uid'], 'id' => $orders['fid'], 'pay_time' => $this->nowTime]);
        }
        //更新2.0订单缓存
        if ($trade_type)
        {
            $orderResData = ['status' => $status, 'pay_time' => $this->nowTime, 'trade_type' => $trade_type, 'transaction_id' => $transactionId, 'extend' => json_encode($extend, JSON_UNESCAPED_UNICODE)];
        } else
        {
            $orderResData = ['status' => $status, 'pay_time' => $this->nowTime, 'transaction_id' => $transactionId, 'extend' => json_encode($extend, JSON_UNESCAPED_UNICODE)];
        }
        $OrdersCacheModel->UpdateData($orders['order_id'], $orderResData, $status);
        //更新优惠券状态
        $this->CheckOrderCoupon($orders);
        //订单支付数量增加
        $OrdersModel->inc_order_num($num, $OrderType);

        //更新星力值
        if ($num !== 6)
        {   // 非会员订单更新星力值  会员星力值已经更新过了
            OrdersLibCacheModel::UpdateVipBoon($orders, $unlock_gid, true);
        }

        //商品购买人数自增,教学视频、本命预测根据gid进行缓存数据
        if (in_array($OrderType, [6, 7, 13], true))
        {
            $OrdersCacheModel->SaveTotalPrepaidOrder($OrderType, $orders['gids']);
        } elseif ($OrderType === 17)
        {   // 合盘报告 根据gid自增 和gid与关系ID【relation_id】新增 维护两个缓存
            $extend = \GuzzleHttp\json_decode($orders['extend'], true);
            $OrdersCacheModel->SaveTotalPrepaidOrder($OrderType, $extend['synastry_report']['srid']); // 根据srid自增
            $OrdersCacheModel->SaveTotalPrepaidOrder($OrderType, $extend['synastry_report']['srid'], $extend['synastry_report']['relation_id']); // 根据srid与关系ID【relation_id自增
        } else
        {
            $OrdersCacheModel->SaveTotalPrepaidOrder($OrderType, 0);
        }

        if ($OrderType === 15)
        {//如果是定制报告，那么发送钉钉消息
            Util::sendZlcrMsg(0, ['微信或者支付宝支付']);
        }
        // 下单做开盲盒活动
//        (new ZlActivePrizeNumIncRecord())->goodsTask($orders['uid'], implode(',', $unlock_gids), $order_id);

        // 记录支付回调日志
        Util::logRealTimeAnalyzeWrite(3, [
            'pay_notify_uid' => $orders['uid'] ?? '',
            'pay_notify_order_id' => $order_id,
            'pay_notify_order_type' => $orders['order_type'] ?? '-1',//1=>校准生辰 2=>日运 3=>月运 4=>年运 5=>幸运之城 6=>教学视频 7=>本命预测 8=>会员购买 9=>准币充值 10=>祈福充值 11=>赠送
            'pay_notify_total_amount' => $total_amount,
            'pay_notify_gid' => implode('-', $unlock_gids),
        ]);
        return true;
    }

    /**
     * 私域H5 订单回调
     * @param string $orderId
     * @param string $totalAmount
     * @return bool
     * @throws Exception
     */
    private function UpdatePrivateAreaOrder(string $orderId, string $totalAmount)
    {
        $privateAreaOrderModel = new PrivateAreaOrders();
        $questionInfoModel = new PrivateAreaQuestionInfo();
        $goodModel = new PrivateAreaGoods();
        $orderInfo = $privateAreaOrderModel->getInfoById($orderId);
        if ((int)$orderInfo['status'] !== 1)
        {
            return true;
        }
        $time = $this->nowTime;
        if (abs($orderInfo['total_amount'] - $totalAmount) > 1)
        {
            Log::write('订单付款金额有疑：订单金额【' . $orderInfo['total_amount'] . '】,回调金额【' . $totalAmount . '】');
            return false;
        }
        // 判断订单状态是否已经更新处理过了
        if (!in_array($orderInfo['status'], [1, 3], true))
        {   // 订单已经处理过了 防止重复处理
            return true;
        }
        // 更新订单状态
        $res = $privateAreaOrderModel->updateOrderInfo($orderId, [
            'status' => 2,
            'pay_time' => $time,
        ]);
        if (!$res)
        {
            return false;
        }
        // 获取咨询信息
        $questionInfo = $questionInfoModel->getPrivateAreaQuestionInfo($orderInfo['qid'], ['uid', 'hash']);
        // 获取私域链接信息
        $goodInfo = $goodModel->getPrivateAreaGoodInfo($questionInfo['hash'], ['lid', 'name', 'aid', 'type']);
        // 更新 私域链接 信息
        $goodModel->updatePrivateAreaLinkData($questionInfo['hash'], $goodInfo['lid'], ['is_pay' => 1]);
        // 更新咨询问题状态
        $questionInfoModel->updateUserQuestionData($orderInfo['qid'], [
            'pay_time' => $time,
            'status' => 2,
        ]);
        $env = Env::get('host.name', 'local');
        $adminName = Db::table('wechatadmin.system_admin_user')->where('id', $goodInfo['aid'])->value('username');
        Util::resDingDingMsgSend('[' . $env . ']派单提醒，用户支付成功，请注意跟进',
            "任务ID：{$orderInfo['qid']} \r\n" .
            "商品名称：{$goodInfo['name']} \r\n" .
            "专属客服：{$adminName}",
            Env::get('host.admin_domain') . '/admin/private_area.task/wait_task.html?id=' . $orderInfo['qid'], 'private_area', 1);
        //  12小时未派单 回调
        Util::queuePush('private_area_dispatch_check', ['qid' => $orderInfo['qid']], 43200);
        return true;
    }

    /**
     * 私域H5实物销售 订单回调
     * @param string $orderId
     * @param string $totalAmount
     * @param int $trade_type
     * @return bool
     * @throws \Exception
     */
    private function UpdatePrivateAreaMallOrder(string $orderId, string $totalAmount, int $trade_type)
    {
        $privateAreaOrderModel = new PrivateAreaOrders();
        $orderInfo = $privateAreaOrderModel->getInfoById($orderId);
        // 判断订单状态是否已经更新处理过了
        if (!in_array($orderInfo['status'], [1, 3], true))
        {   // 订单已经处理过了 防止重复处理
            return true;
        }
        $time = $this->nowTime;
        if (abs($orderInfo['total_amount'] - $totalAmount) > 1)
        {
            Log::write('订单付款金额有疑：订单金额【' . $orderInfo['total_amount'] . '】,回调金额【' . $totalAmount . '】');
            return false;
        }
        $updateOrder = [
            'trade_type' => $trade_type,    // 1=>支付宝 2=>支付
            'status' => 2,
            'inventory_status' => 1,
            'kd_status' => 1,
            'pay_time' => $time,
        ];
        $privateAreaMallGoodsAttrModel = new PrivateAreaMallGoodsAttr();
        $goodAttrDetail = $privateAreaMallGoodsAttrModel->getInfoById($orderInfo['qid']);
        $updateOrder['shipping_type'] = $goodAttrDetail['shipping_type'];
        // 更新订单状态
        $res = $privateAreaOrderModel->updateOrderInfo($orderId, $updateOrder);
        if (!$res)
        {
            return false;
        }
        // 增加销售量
        $d = [
            'num' => $goodAttrDetail['num'] + 1,
        ];
        if ($orderInfo['status'] === 3)
        {   // 扣除库存
            $d['inventory'] = $goodAttrDetail['inventory'] - 1;
        }
        $privateAreaMallGoodsAttrModel->UpdateData($orderInfo['qid'], $d);

        return true;
    }

    /**
     * 生时矫正入队
     * @param $orders
     * @param $order_id
     * @throws Exception
     */
    private function rec($orders, $order_id)
    {
        (new Rectification())->saveRec($orders['uid'], $orders['reid'], ['status' => 1]);
        $userinfo['id'] = $orders['uid'];
        // 付款成功  开始校准生辰
        (new PushQueue())->Rectification($userinfo, $orders['reid'], $orders['id'], $order_id);
    }

    /**
     * 运势入队
     * @param $orders
     * @throws Exception
     */
    private function FortuneQueue($orders)
    {
        // 付款成功  开始添加运势计算
        (new PushQueue)->Fortune(['uid' => $orders['uid'], 'oid' => $orders['id']]);
    }

    /**
     * 地图入队
     * @param $orders
     */
    private function MapQueue($orders)
    {
        (new PushQueue())->Map($orders['order_id']);
    }

    /**
     * 本命预测入队加结果数据写入
     * @param array $orders
     * @param array $unlock_gids
     * @param string $order_id
     * @param null $queueDelay 队列延迟时间
     * @throws Exception
     */
    private function NatalQueue($orders, $unlock_gids, $order_id, $queueDelay = null)
    {
        $NatalReportModel = new NatalReport();
        $NatalReportModel->SaveQueue($orders['uid'], $orders['rid'], $unlock_gids, $order_id, $queueDelay);
    }

    /**
     * 本命预测入队加结果数据写入
     * @param array $orders
     * @param int $unlock_gid
     * @param null $queueDelay 队列延迟时间
     * @throws Exception
     */
    private function SynastryQueue(array $orders, int $unlock_gid, $queueDelay = null)
    {
        $extend = \GuzzleHttp\json_decode($orders['extend'], true);
        (new ZlSynastryReport())->SaveQueue((int)$orders['uid'], $unlock_gid, $extend['synastry_report'], $orders['order_id'], $queueDelay);
    }

    /**
     * 定制报告入队
     * @param $orders
     * @throws Exception
     */
    private function customReport($orders)
    {
        $questionModel = new ZlcrCustomReportQuestion();
        $questionModel->orderReportQueue($orders['order_id']);
    }

    /**
     * 更新vip状态
     * @param $orders
     * @param $gid
     */
    private function Vip($orders, $gid)
    {
        OrdersLibCacheModel::UpdateVipStatus($orders, $gid);
    }

    /**
     * 获取订单和商品信息
     * @param $order_id
     * @return array
     */
    public function GetOrdersGoodsInfo($order_id)
    {
        //获取订单信息
        try
        {
            $field = 'o.id,o.status,o.order_type,o.uid,o.gid,o.order_id,o.fid,o.reid,o.total_amount,o.extend,og.gid gids,og.rid,o.env_type';
            $orders = (new OrdersCacheModel())
                ->alias('o')
                ->field($field)
                ->join('wechat_backup_07_18_14_43_00.app_orders_goods og', 'o.id=og.oid', 'LEFT')
                ->where('o.order_id', $order_id)
                ->selectOrFail();
            $orders = json_decode(json_encode($orders, true), true);
        }
        catch (Exception $e)
        {
            Log::write($order_id . '回调获取订单相关信息失败：' . $e->getMessage() . '错误行数：' . $e->getLine(), 'error', true);
            $orders = [];
        }

        return $orders;
    }

    /**
     * 检测订单是否使用优惠券，并更改优惠券状态
     * @param $orders
     * @return bool
     */
    private function CheckOrderCoupon($orders)
    {
        //若订单使用了优惠券则将优惠券改为已使用
        try
        {
            $extend = $orders['extend'] ? json_decode($orders['extend'], true) : [];
            $order_coupon = $extend['coupon'] ?? '';//获取订单的优惠券id
            if ($order_coupon)
            {
                $UserCouponModel = new UserCoupon();
                $UserCouponModel->use_return($orders['uid'], $order_coupon['cid'], ['status' => 1, 'update_time' => $this->nowTime]);
            }
            return true;
        }
        catch (Exception $e)
        {
            return false;
        }
    }

    /**
     * 判断订单类型
     * @param $order_id
     * @return int
     */
    private function check_type($order_id): int
    {

        $num = substr($order_id, 0, 2);

        return (int)$num;
    }

    /**
     * 订单相关打点
     * @param $order_id string 订单号
     * @param $event string 打点事件类型：[buy_confirm => 确认订单｜buy_success => 购买成功]
     */
    public function getSensorsTrackData($order_id = '', $event = ''): void
    {
        try
        {
            $uid = 0;
            $orderPrefix = $this->check_type($order_id);
            switch ($orderPrefix)
            {
                case 1:#校准生辰购买成功
                    #神策打点 55 生时校正成功支付 RectificationBuySuccess
                    $eventNameList = [
                        'buy_confirm' => 'RectificationBuyConfirm',
                        'buy_success' => 'RectificationBuySuccess',
                    ];
                    // 获取校准生辰订单信息
                    $res = (new OrdersCacheModel())
                        ->alias('o')
                        ->join('wechat_backup_07_18_14_43_00.app_rectification re', 'o.reid=re.id')
                        ->join('wechat_backup_07_18_14_43_00.app_recode r', 're.rid=r.id')
                        ->join('wechat_backup_07_18_14_43_00.app_goods g', 'o.gid=g.id')
                        ->where('order_id', $order_id)
                        ->field('o.uid,o.reid,o.extend,o.trade_type,o.total_amount,g.now_prize,r.name,r.id rid,r.year,r.month,r.day,re.start_time,re.end_time,r.is_summer')
                        ->findOrFail()
                        ->toArray();
                    $uid = $res['uid'];
                    $eventNum = (new RectificationEvent())->where(['reid' => $res['reid']])->count('id');

                    $sensorsTrackData = [
                        'record_name' => $res['name'],// 档案名称
                        'record_id' => (int)$res['rid'],// 档案ID
                        'birth_year' => $res['year'],// 出生年份
                        'birth_month' => $res['month'],// 出生月份
                        'birth_day' => $res['day'],// 出生日期
                        'start_time' => date('Y-m-d H:i:s', $res['start_time']),// 出生时间左
                        'end_time' => date('Y-m-d H:i:s', $res['end_time']),// 出生时间右
                        'is_summer' => $res['is_summer'] ? true : false,// 是否为夏令时
                        'event_num' => $eventNum * 1,// 重大事件数量
                        'goods_price' => $res['now_prize'] * 1,// 商品单价
                        'goods_total' => $res['now_prize'] * 1,// 商品总价
                    ];
                    $this->getSensorsTrackCommonData($sensorsTrackData, $order_id, $res, $event);

                    $trackData[] = [
                        'eventName' => $eventNameList[$event] ?? '',
                        'eventData' => $sensorsTrackData,
                    ];
                    break;
                case 2:#每日/月度/年度 运势购买成功
                    #神策打点 35 日/月/年运势成功支付 RecordFortuneBuySuccess
                    $eventNameList = [
                        'buy_confirm' => 'RecordFortuneBuyConfirm',
                        'buy_success' => 'RecordFortuneBuySuccess',
                    ];
                    // 获取运势订单信息
                    $res = (new OrdersCacheModel())
                        ->alias('o')
                        ->join('wechat_backup_07_18_14_43_00.app_fortune f', 'o.fid=f.id')
                        ->join('wechat_backup_07_18_14_43_00.app_goods g', 'o.gid=g.id')
                        ->where('order_id', $order_id)
                        ->field('o.uid,o.extend,o.trade_type,o.order_type,o.total_amount,o.gid,g.now_prize,g.name gname,f.type,f.time,f.rids')
                        ->findOrFail()
                        ->toArray();
                    $uid = $res['uid'];
                    $rids = explode(',', $res['rids']);

                    $recode = (new Recode())->where(['id' => ['in', $rids]])->field('name,id rid,year,month,day,is_summer')->findOrFail()->toArray();

                    if ($res['order_type'] == 2)
                    {
                        $fname = '每日运势';
                        $fortuneTime = date('Y-m-d', $res['time']);// 选择时间
                    } elseif ($res['order_type'] == 3)
                    {
                        $fname = '月度运势';
                        $fortuneTime = date('Y-m', $res['time']);// 选择时间
                    } elseif ($res['order_type'] == 4)
                    {
                        $fname = '年度运势';
                        $fortuneTime = date('Y', $res['time']);// 选择时间
                    }

                    $sensorsTrackData = [
                        'fortune_type' => $fname ?? '',// 运势类型
                        'record_name' => $recode['name'],// 档案名称
                        'record_id' => (int)$recode['rid'],// 档案ID
                        'fortune_time' => $fortuneTime ?? '',// 选择时间
                        'fortune_goods' => $res['gname'],// 购买类型
                        'goods_price' => $res['now_prize'] * 1,// 商品单价
                        'goods_total' => $res['now_prize'] * count($rids),// 商品总价
                    ];
                    $this->getSensorsTrackCommonData($sensorsTrackData, $order_id, $res, $event);

                    $trackData[] = [
                        'eventName' => $eventNameList[$event] ?? '',
                        'eventData' => $sensorsTrackData,
                    ];
                    break;
                case 3:#幸运之城购买成功
                    #神策打点 48 幸运之城成功支付 LuckyMapBuySuccess
                    $eventNameList = [
                        'buy_confirm' => 'LuckyMapBuyConfirm',
                        'buy_success' => 'LuckyMapBuySuccess',
                        'buy_confirm_detail' => 'LuckyMapBuyConfirmDetails',
                        'buy_success_detail' => 'LuckyMapBuySuccessDetails',
                    ];
                    // 获取订单信息
                    $res = (new OrdersCacheModel())
                        ->alias('o')
                        ->join('wechat_backup_07_18_14_43_00.app_orders_goods og', 'o.id=og.oid')
                        ->join('wechat_backup_07_18_14_43_00.app_goods g', 'og.gid=g.id')
                        ->join('wechat_backup_07_18_14_43_00.app_recode r', 'og.rid=r.id')
                        ->where('order_id', $order_id)
                        ->field('o.uid,o.extend,o.trade_type,o.total_amount,g.now_prize,r.name,r.id rid,r.year,r.month,r.day,r.is_summer,g.name gname,g.now_prize,og.gid')
                        ->selectOrFail();
                    $res = json_decode(json_encode($res, true), true);
                    $goodsPriceList = [];
                    foreach ($res as $v1)
                    {
                        $goodsPriceList[] = (string)$v1['now_prize'];
                    }
                    $goodsNameList = array_column($res, 'gname');
                    $rname = implode(',', array_unique(array_column($res, 'name')));
                    $rid = implode(',', array_unique(array_column($res, 'rid')));
                    $goods_total = array_sum(array_column($res, 'now_prize'));
                    $gids = array_column($res, 'gid');
                    $sensorsTrackData = [
                        'unlock_type' => in_array(19, $gids, false) ? '打包解锁' : '自选解锁',// 解锁方式,打包
                        'goods_name_list' => $goodsNameList,// 自选解锁内容
                        'record_name' => $rname,// 档案名称
                        'record_id' => (int)$rid,// 档案ID
                        'goods_price_list' => $goodsPriceList,// 商品单价
                        'goods_total' => $goods_total * 1,// 商品总价
                    ];
                    $resOne = current($res);
                    $uid = $resOne['uid'];
                    $this->getSensorsTrackCommonData($sensorsTrackData, $order_id, $resOne, $event);
                    $trackData[] = [
                        'eventName' => $eventNameList[$event] ?? '',
                        'eventData' => $sensorsTrackData,
                    ];
                    # 神策打点 49 幸运之城多选解锁详情 LuckyMapBuySuccessDetail
                    # 多选解锁时，每选择一个需要打一次点
                    //计算商品打折前的原价
                    $orPrice = array_sum(array_column($res, 'now_prize'));
                    //计算优惠折扣
                    $discount = $resOne['total_amount'] / $orPrice;
                    foreach ($res as $re)
                    {
                        //计算商品打折后的价格
                        $goodsDisPrice = $re['now_prize'] * $discount;
                        $trackData[] = [
                            'eventName' => $eventNameList[$event . '_detail'] ?? '',
                            'eventData' => [
                                'goods_name' => $re['gname'],// 命格线类型
                                'record_name' => $re['gname'],// 档案名称
                                'record_id' => (int)$re['rid'],// 档案ID
                                'goods_price' => $re['now_prize'] * 1,// 商品单价
                                'order_id' => $order_id,// 订单编号
                                'trade_type' => $re['trade_type'],// 支付方式
                                'weight_percent' => $re['now_prize'] / $orPrice,// 权重占比
                                'weight_price' => $re['now_prize'] - $goodsDisPrice,// 权重优惠金额
                                'total_amount' => $goodsDisPrice,// 实付金额
                            ],
                        ];
                    }
                    break;
                case 4:#教学视频
                    #神策打点 视频支付成功
                    // 获取订单信息
                    $res = (new OrdersCacheModel())
                        ->where('order_id', $order_id)
                        ->field('uid,trade_type,total_amount,gid,extend')
                        ->findOrFail()
                        ->toArray();
                    $uid = $res['uid'];

                    $goodsInfo = (new Goods())->getInfoById($res['gid']);
                    $eventNameList = [
                        'buy_confirm' => 'CourseBuyConfirm',
                        'buy_success' => 'CourseBuySuccess',
                    ];

                    $sensorsTrackData = [
                        'goods_type' => '教学视频',
                        'goods_name' => $goodsInfo['name'],// 商品名称
                    ];
                    $this->getSensorsTrackCommonData($sensorsTrackData, $order_id, $res, $event);
                    $trackData[] = [
                        'eventName' => $eventNameList[$event] ?? '',
                        'eventData' => $sensorsTrackData,
                    ];
                    break;
                case 5:#一生报告购买成功
                    #神策打点 84 一生报告支付成功 NatalReportBuySuccess
                    $eventNameList = [
                        'buy_confirm' => 'NatalReportBuyConfirm',
                        'buy_success' => 'NatalReportBuySuccess',
                        'buy_confirm_detail' => 'NatalReportBuyConfirmDetails',
                        'buy_success_detail' => 'NatalReportBuySuccessDetails',
                    ];
                    // 获取订单信息
                    $res = (new OrdersCacheModel())
                        ->alias('o')
                        ->join('wechat_backup_07_18_14_43_00.app_orders_goods og', 'o.id=og.oid', 'inner')
                        ->join('wechat_backup_07_18_14_43_00.app_goods g', 'og.gid=g.id', 'inner')
                        ->join('wechat_backup_07_18_14_43_00.app_recode r', 'og.rid=r.id', 'inner')
                        ->where('o.order_id', $order_id)
                        ->field('og.rid,o.uid,o.trade_type,o.total_amount,o.extend,g.name gname,r.name rname,g.now_prize')
                        ->selectOrFail();

                    $res = json_decode(json_encode($res, true), true);

                    $num = count($res);
                    $sensorsTrackData = [
                        'record_name' => $res[0]['rname'],// 档案名称
                        'record_id' => (int)$res[0]['rid'],// 档案ID
                        'unlock_type' => $num > 1 ? '多选' : '单选',// 解锁方式,多选，单选
                        'unlock_num' => $num,// 解锁数量
                    ];
                    $resOne = current($res);
                    $uid = $resOne['uid'];
                    $this->getSensorsTrackCommonData($sensorsTrackData, $order_id, $resOne, $event);
                    $trackData[] = [
                        'eventName' => $eventNameList[$event] ?? '',
                        'eventData' => $sensorsTrackData,
                    ];
                    # 神策打点 85 一生报告支付成功详情 NatalReportBuySuccessDetails
                    # 多选解锁时，每选择一个需要打一次点
                    //计算商品原总价
                    $orPrice = array_sum(array_column($res, 'now_prize'));
                    //计算优惠折扣
                    $discount = $resOne['total_amount'] / $orPrice;
                    foreach ($res as $re)
                    {
                        //计算商品打折后的价格
                        $goodsDisPrice = $re['now_prize'] * $discount;
                        $trackData[] = [
                            'eventName' => $eventNameList[$event . '_detail'] ?? '',
                            'eventData' => [
                                'unlock_report' => $re['gname'],// 解锁报告类型
                                'record_name' => $re['rname'],// 档案名称
                                'record_id' => (int)$re['rid'],// 档案ID
                                'is_use_coupon' => $sensorsTrackData['is_use_coupon'],// 是否使用优惠券
                                'coupon_type' => $sensorsTrackData['coupon_type'],// 优惠券类型
                                'is_official_active' => $sensorsTrackData['is_official_active'],// 是否有官方活动
                                'goods_price' => $re['now_prize'] * 1,// 商品单价
                                'order_id' => $order_id,// 订单编号
                                'trade_type' => $re['trade_type'],// 支付方式
                                'weight_percent' => $re['now_prize'] / $orPrice,// 权重占比
                                'weight_price' => $re['now_prize'] - $goodsDisPrice,// 权重优惠金额
                                'total_amount' => $goodsDisPrice,// 实付金额
                            ],
                        ];
                    }
                    break;
                case 6:#会员购买成功 06202103050901441583
                    #神策打点 86 会员支付成功 VipBuySuccess
                    $eventNameList = [
                        'buy_confirm' => 'VipBuyConfirm',
                        'buy_success' => 'VipBuySuccess',
                    ];
                    //  获取会员购买订单信息
                    $res = (new OrdersCacheModel())
                        ->alias('o')
                        ->join('wechat_backup_07_18_14_43_00.app_goods g', 'o.gid=g.id', 'inner')
                        ->where('o.order_id', $order_id)
                        ->field('o.uid,o.gid,o.extend,o.trade_type,o.total_amount,g.name,g.now_prize')
                        ->findOrFail()
                        ->toArray();
                    $uid = $res['uid'];
                    $timeInfo = OrdersLibCacheModel::getUserVipTime($res['uid'], $res['gid']);
                    $sensorsTrackData = [
                        'goods_name' => $res['name'],// 购买类型
                        'goods_price' => $res['now_prize'] * 1,// 商品单价
                        'end_time' => date('Y-m-d H:i:s', $timeInfo['vip_end_time']),// 到期时间
                    ];
                    $this->getSensorsTrackCommonData($sensorsTrackData, $order_id, $res, $event);
                    $trackData[] = [
                        'eventName' => $eventNameList[$event] ?? '',
                        'eventData' => $sensorsTrackData,
                    ];
                    break;
                case 7:#准币充值成功  07202001131720542110
                    #神策打点 64 钱包成功充值  WalletRechargeSuccess
                    $eventNameList = [
                        'buy_confirm' => '',
                        'buy_success' => 'WalletRechargeSuccess',
                    ];
                    // 获取准币订单信息
                    $res = (new ZhunleUserAccountRecord())
                        ->where(['order_id' => $order_id])
                        ->field('total_amount,coin_num,uid,order_id,trade_type')
                        ->findOrFail()
                        ->toArray();
                    $uid = $res['uid'];
                    $sensorsTrackData = [
                        'goods_name' => $res['coin_num'] . '准币',// 充值类型
                    ];
                    $this->getSensorsTrackCommonData($sensorsTrackData, $order_id, $res, $event);
                    $trackData[] = [
                        'eventName' => $eventNameList[$event] ?? '',
                        'eventData' => $sensorsTrackData,
                    ];
                    break;
                case 8:#万幸商城支付成功
                    #神策打点 69 商品成功支付 MallGoodsBuySuccess
                    $eventNameList = [
                        'buy_confirm' => 'MallGoodsBuyConfirm',
                        'buy_success' => 'MallGoodsBuySuccess',
                    ];
                    // 获取万幸商城订单信息
                    $res = (new OrdersCacheModel())
                        ->alias('o')
                        ->join('wechat_backup_07_18_14_43_00.mall_goods_attr gr', 'o.gid=gr.id', 'inner')
                        ->where('o.order_id', $order_id)
                        ->field('o.extend,o.gid,o.uid,o.total_amount,o.trade_type,gr.name,gr.now_price,gr.inventory')
                        ->findOrFail()
                        ->toArray();
                    $uid = $res['uid'];
                    $extend = (new OrdersCacheModel())->getMallExtend($res);
                    $address = explode('，', $extend['address']);
                    $goods = (new MallGoods())
                        ->alias('g')
                        ->join('wechat_backup_07_18_14_43_00.mall_channel c', 'g.channel_id=c.id', 'LEFT')
                        ->where('g.id', $extend['mall_gid'])
                        ->field('g.name gname,c.name cname,c.id cid')
                        ->findOrFail()
                        ->toArray();
                    $sensorsTrackData = [
                        'goods_name' => $goods['gname'],// 商品名称
                        'specification_name' => $res['name'],// 规格样式
                        'goods_total' => $res['now_price'] * $extend['num'],// 规格总价
                        'goods_price' => $res['now_price'] * 1,// 规格单价
                        'goods_id' => (int)$res['gid'],// 规格ID
                        'goods_inventory' => (int)$res['inventory'],// 规格库存
                        'supplier_name' => $goods['cname'],// 供应商名称
                        'supplier_id' => (int)$goods['cid'],// 供应商ID
                        'buy_num' => $extend['num'],// 购买数量
                        'receiver_name' => $extend['name'],// 收货人姓名
                        'receiver_tel' => $extend['phone'],// 收货人手机号
                        'receiver_province' => $address[0] ?? '',// 收货省份
                        'receiver_city' => $address[1] ?? '',// 收货市区
                        'receiver_address' => ($address[2] ?? '') . ($address[3] ?? ''),// 具体地址
//                        'express_name' => $extend['kd_name'],// 快递机构
//                        'express_price' => $extend['kd_price'],// 快递费
                    ];
                    $this->getSensorsTrackCommonData($sensorsTrackData, $order_id, $res, $event);
                    $trackData[] = [
                        'eventName' => $eventNameList[$event] ?? '',
                        'eventData' => $sensorsTrackData,
                    ];
                    break;
                case 9:#定制报告
                    #神策打点 98 定制报告确认下单 CustomReportBuyConfirm
                    #神策打点 99 定制报告支付成功 CustomReportBuySuccess
                    $eventNameList = [
                        'buy_confirm' => 'CustomReportBuyConfirm',
                        'buy_success' => 'CustomReportBuySuccess',
                    ];
                    $question = (new ZlcrCustomReportQuestion())->alias('q')
                        ->join('wechat_backup_07_18_14_43_00.zlcr_custom_report_question_info qi', 'q.id=qi.qid')
                        ->field('q.question_name,q.id,qi.recode_info')
                        ->where('q.order_num', $order_id)
                        ->findOrFail()->toArray();
                    $recodeList = json_decode($question['recode_info'], true);
                    $res = (new OrdersCacheModel())->field('uid,extend,total_amount,trade_type')->where('order_id', $order_id)->find();
                    $uid = $res['uid'];
                    $sensorsTrackData = [
                        'question_name' => $question['question_name'],
                        'question_id' => $question['id'],
                        'record1_name' => $recodeList['recode1']['name'] ?? '无',
                        'record1_id' => $recodeList['recode1']['id'] ?? 0,
                        'record2_name' => $recodeList['recode2']['name'] ?? '无',
                        'record2_id' => $recodeList['recode2']['id'] ?? 0,
                    ];
                    $this->getSensorsTrackCommonData($sensorsTrackData, $order_id, $res, $event);
                    $trackData[] = [
                        'eventName' => $eventNameList[$event] ?? '',
                        'eventData' => $sensorsTrackData,
                    ];
                    break;
                case 11:#合盘报告
                    #神策打点 92 合盘报告提交购买 SynastryReportBuyConfirm
                    #神策打点 93 合盘报告支付成功 SynastryReportBuySuccess
                    $eventNameList = [
                        'buy_confirm' => 'SynastryReportBuyConfirm',
                        'buy_success' => 'SynastryReportBuySuccess',
                    ];
                    // 获取订单信息
                    $res = (new OrdersCacheModel())
                        ->alias('o')
                        ->where('o.order_id', $order_id)
                        ->field('o.uid,o.trade_type,o.total_amount,o.gid,o.extend')
                        ->findOrFail()
                        ->toArray();
                    $uid = $res['uid'];
                    $extend = json_decode($res['extend'], true);
                    $recodeModel = new Recode();
                    $recordInfo1 = $recodeModel->getInfoById($extend['synastry_report']['rid1'], ['id', 'uid', 'name']);
                    $recordInfo2 = $recodeModel->getInfoById($extend['synastry_report']['rid2'], ['id', 'uid', 'name']);
                    $sensorsTrackData = [
                        'record1_name' => $recordInfo1['name'],// 档案名称1	 STRING
                        'record1_id' => $extend['synastry_report']['rid1'],// 档案ID1	 NUMBER
                        'record2_name' => $recordInfo2['name'],// 档案名称2	 STRING
                        'record2_id' => $extend['synastry_report']['rid2'],// 档案ID2	 NUMBER
                        'report_name' => '',// 报告类型 	 STRING 	暗恋对象、正在热恋、已经分手、步入婚姻
                        'time_range' => '',// 计算周期	STRING	未来一年、未来三年、未来五年、未来十年
                        'begin_time' => (int)$extend['synastry_report']['start_time'],// 开始时间	DATETIME	'2021-04-01 00:00:00'
                    ];
                    $synastryReportConfig = config('synastryreport');
                    $relations = ['', '暗恋对象', '正在热恋', '已经分手', '步入婚姻'];
                    foreach ($synastryReportConfig[1]['good_list'] as $k => $v)
                    {
                        if ($res['gid'] === $k)
                        {
                            $sensorsTrackData['report_name'] = $relations[$v['relation_id']];
                            $sensorsTrackData['time_range'] = $v['name_desc'];
                        }
                    }
                    $this->getSensorsTrackCommonData($sensorsTrackData, $order_id, $res, $event);

                    $trackData[] = [
                        'eventName' => $eventNameList[$event] ?? '',
                        'eventData' => $sensorsTrackData,
                    ];
                    break;
                case 12:
                case 13:
                case 14:
                    #神策打点 解答提交成功 LiveQuestionBuyConfirm
                    #神策打点 解答支付成功 LiveQuestionApplySuccess
                    $eventNameList = [
                        'buy_confirm' => 'LiveQuestionBuyConfirm',
                        'buy_success' => 'LiveQuestionApplySuccess',
                    ];
                    // 获取订单信息
                    $res = (new OrdersCacheModel())
                        ->alias('o')
                        ->where('o.order_id', $order_id)
                        ->field('o.uid,o.trade_type,o.total_amount,o.extend')
                        ->findOrFail()
                        ->toArray();
                    $uid = $res['uid'];
                    $answerModel = null;
                    $extend = json_decode($res['extend'], true);
                    if (isset($extend['live_info']))
                    {
                        $liveId = (int)$extend['live_info']['live_id'];
                        $liveRecordId = (int)$extend['live_info']['live_record_id'];
                        $liveName = $extend['live_info']['name'];
                    }
                    switch ($orderPrefix)
                    {
                        case 12:
                            $answerModel = new LiveAnswerAstroRecord();
                            $history = $answerModel->where(['order_num' => $order_id])->field('extend,question,question_des')->find();

                            $recode = json_decode($history['extend'], true);
                            if (isset($recode['recode1']) && $recode['recode1'])
                            {
                                $recodeId1 = (int)$recode['recode1']['id'];
                                $recodeName1 = $recode['recode1']['name'];
                            }
                            if (isset($recode['recode2']) && $recode['recode2'])
                            {
                                $recodeId2 = (int)$recode['recode2']['id'];
                                $recodeName2 = $recode['recode2']['name'];
                                $is_synastry = true;
                            }
                            $sensorsTrackData['LiveQuestionApplySuccess'] = [];
                            $typeName = '看盘';
                            break;
                        case 13:
                            $answerModel = new LiveAnswerDiceRecord();
                            $history = $answerModel->where(['order_num' => $order_id])->field('question')->find();
                            $typeName = '骰子';
                            break;
                        case 14:
                            $answerModel = new LiveAnswerTarotRecord();
                            $history = $answerModel->where(['order_num' => $order_id])->field('question')->find();
                            $typeName = '塔罗';
                            break;
                    }
                    $sensorsTrackData['LiveQuestionBuyConfirm'] = [
                        'hoster_name' => $liveName ?? '',
                        'live_id' => $liveId ?? 0,
                        'live_record_id' => $liveRecordId ?? 0,
                        'record1_name' => $recodeName1 ?? '',
                        'record1_id' => $recodeId1 ?? 0,
                        'record2_name' => $recodeName2 ?? '',
                        'record2_id' => $recodeId2 ?? 0,
                        'order_id' => $order_id,
                        'trade_type' => (int)$res['trade_type'],
                        'is_success' => true,
                        'failed_reason' => '',
                        'question_type' => $typeName ?? '',
                    ];
                    $sensorsTrackData['LiveQuestionApplySuccess'] = [
                        'hoster_name' => $liveName ?? '',
                        'live_id' => $liveId ?? 0,
                        'live_record_id' => $liveRecordId ?? 0,
                        'is_synastry' => $is_synastry ?? false,
                        'question_type' => $typeName ?? '',
                        'price' => $res['total_amount'] * 1,
                        'question' => $history['question'] ?? '',
                        'description' => $history['question_des'] ?? '无',
                    ];
                    $trackData[] = [
                        'eventName' => $eventNameList[$event] ?? '',
                        'eventData' => $sensorsTrackData[$eventNameList[$event]] ?? [],
                    ];
                    break;
                case 15:
                    $questionModel = new Zlcr2UserQuestion();
                    $ordersModel = new OrdersCacheModel();
                    $orders = $ordersModel->where('order_id', $order_id)->field('uid,fid,gid,trade_type,total_amount,extend')->find();
                    $question = $questionModel::withTrashed()->where('id', $orders['fid'])->field('id,question_type,gid,is_anonymity,question_imgs,question,question_des,answer_duration')->find();
                    $qtype = $questionModel->getQuestionType((int)$orders['gid']);
                    $uid = $orders['uid'];
                    switch ($qtype['type'])
                    {
                        case 1://蹭看
                            #神策打点 蹭看提交成功 QuestionViewPayConfirm
                            #神策打点 蹭看支付成功 QuestionViewPaySuccess
                            $eventNameList = [
                                'buy_confirm' => 'QuestionViewPayConfirm',
                                'buy_success' => 'QuestionViewPaySuccess',
                            ];
                            $sensorsTrackData = [
                                'question_id' => $question['id'],
                                'author_id' => $orders['uid'],//提问者id
                                'question_type' => $question['question_type'],
                            ];
                            break;
                        case 2://追问
                            #神策打点 追问提交成功 QuestionEvaluationPayConfirm
                            #神策打点 追问支付成功 QuestionEvaluationPaySuccess
                            $eventNameList = [
                                'buy_confirm' => 'QuestionEvaluationPayConfirm',
                                'buy_success' => 'QuestionEvaluationPaySuccess',
                            ];
                            $sensorsTrackData = [
                                'question_id' => $question['id'],
                                'question_type' => $question['question_type'],
                                'is_voice' => $question['answer_duration'] > 0,//是否为语音回复
                            ];
                            break;
                        case 3://问答
                            #神策打点 问答提交成功 QuestionAddPayConfirm
                            #神策打点 问答支付成功 QuestionAddPaySuccess
                            $questionGoods = Util::getZhunleQuestionAnswerConfig();
                            $price = $questionGoods[$question['gid']]['price'] ?? 0;
                            $eventNameList = [
                                'buy_confirm' => 'QuestionAddPayConfirm',
                                'buy_success' => 'QuestionAddPaySuccess',
                            ];
                            $sensorsTrackData = [
                                'is_anonymous' => $question['is_anonymity'] > 0,//是否匿名
                                'is_added_photo' => $question['question_imgs'] ? true : false,//是否添加了图片
                                'question_title' => $question['question'],
                                'question_type' => $question['question_type'],
                                'price' => $price,//套餐价格
                                'question_des' => $question['question_des'],
                            ];
                            break;
                    }
                    if (isset($eventNameList))
                    {
                        $this->getSensorsTrackCommonData($sensorsTrackData, $order_id, $orders, $event);
                        $trackData[] = [
                            'eventName' => $eventNameList[$event] ?? '',
                            'eventData' => $sensorsTrackData,
                        ];
                    } else
                    {
                        $trackData = [];
                    }
                    break;
                case 16://适合你的TA
                    $eventNameList = [
                        'buy_confirm' => 'SuitableLoverBuyConfirm',
                        'buy_success' => 'SuitableLoverBuySuccess',
                    ];
                    // 获取订单信息
                    $res = (new OrdersCacheModel())
                        ->alias('o')
                        ->join('wechat_backup_07_18_14_43_00.app_orders_goods og', 'o.id=og.oid', 'inner')
                        ->join('wechat_backup_07_18_14_43_00.app_goods g', 'og.gid=g.id', 'inner')
                        ->join('wechat_backup_07_18_14_43_00.app_recode r', 'og.rid=r.id', 'inner')
                        ->where('o.order_id', $order_id)
                        ->field('og.rid,o.uid,o.trade_type,o.total_amount,o.extend,g.name gname,r.name rname,g.now_prize')
                        ->selectOrFail();
                    $res = json_decode(json_encode($res, true), true);
                    $oneRe = current($res);
                    $uid = $oneRe['uid'];
                    $sensorsTrackData = [
                        'record_name' => $oneRe['rname'],
                        'record_id' => $oneRe['rid'],
                        'unlock_list' => array_column($res, 'gname'),
                    ];
                    $this->getSensorsTrackCommonData($sensorsTrackData, $order_id, $oneRe, $event);
                    $trackData[] = [
                        'eventName' => $eventNameList[$event] ?? '',
                        'eventData' => $sensorsTrackData,
                    ];
                    break;
                case 17://你的理想型
                    $eventNameList = [
                        'buy_confirm' => 'IdealLoverBuyConfirm',
                        'buy_success' => 'IdealLoverBuySuccess',
                    ];
                    // 获取订单信息
                    $res = (new OrdersCacheModel())
                        ->alias('o')
                        ->where('o.order_id', $order_id)
                        ->field('o.uid,o.trade_type,o.total_amount,o.gid,o.extend')
                        ->findOrFail()
                        ->toArray();
                    $uid = $res['uid'];
                    $extend = json_decode($res['extend'], true);
                    $ridsNum = count(explode(',', $extend['relation_idea_info']['rids']));
                    $tagTmp = json_decode($extend['relation_idea_info']['tag_info'], true);
                    $tagIds = array_values($tagTmp);
                    $tagInfo = (new Zl1IdeaTag())->batchGetInfoByIds($tagIds, ['id', 'name', 'type']);
                    $sensorsTrackData = [
                        'record_num' => $ridsNum,
                        'tag_list' => array_column($tagInfo, 'name'),
                    ];
                    $this->getSensorsTrackCommonData($sensorsTrackData, $order_id, $res, $event);

                    $trackData[] = [
                        'eventName' => $eventNameList[$event] ?? '',
                        'eventData' => $sensorsTrackData,
                    ];
                    break;
                case 18://怎么追求TA
                    $eventNameList = [
                        'buy_confirm' => 'HowToWooHimBuyConfirm',
                        'buy_success' => 'HowToWooHimBuySuccess',
                    ];
                    // 获取订单信息
                    $res = (new OrdersCacheModel())
                        ->alias('o')
                        ->where('o.order_id', $order_id)
                        ->field('o.uid,o.trade_type,o.total_amount,o.gid,o.extend')
                        ->findOrFail()
                        ->toArray();
                    $uid = $res['uid'];
                    $extend = json_decode($res['extend'], true);
                    $ridsInfo = $extend['recode_ids'];
                    $recodeInfo = (new Recode())->batchGetInfoByIds([$ridsInfo['rid1'], $ridsInfo['rid2']]);
                    $sensorsTrackData = [
                        'record1_name' => $recodeInfo[$ridsInfo['rid1']]['name'],
                        'record1_id' => (int)$recodeInfo[$ridsInfo['rid1']]['id'],
                        'record2_name' => $recodeInfo[$ridsInfo['rid2']]['name'],
                        'record2_id' => (int)$recodeInfo[$ridsInfo['rid2']]['id'],
                    ];
                    $this->getSensorsTrackCommonData($sensorsTrackData, $order_id, $res, $event);

                    $trackData[] = [
                        'eventName' => $eventNameList[$event] ?? '',
                        'eventData' => $sensorsTrackData,
                    ];
                    break;
                case 19://鉴渣神器
                    $eventNameList = [
                        'buy_confirm' => 'AuthenticatePlayboyBuyConfirm',
                        'buy_success' => 'AuthenticatePlayboyBuySuccess',
                    ];
                    // 获取订单信息
                    $res = (new OrdersCacheModel())
                        ->alias('o')
                        ->join('wechat_backup_07_18_14_43_00.app_orders_goods og', 'o.id=og.oid', 'inner')
                        ->where('o.order_id', $order_id)
                        ->field('og.rid,o.uid,o.trade_type,o.total_amount,o.extend')
                        ->selectOrFail();
                    $res = current($res);
                    $uid = $res['uid'];
                    $recode = (new Recode())->getInfoById($res['rid']);
                    $sensorsTrackData = [
                        'record_name' => $recode['name'],
                        'record_id' => (int)$recode['id'],
                    ];

                    $this->getSensorsTrackCommonData($sensorsTrackData, $order_id, $res, $event);

                    $trackData[] = [
                        'eventName' => $eventNameList[$event] ?? '',
                        'eventData' => $sensorsTrackData,
                    ];
                    break;
            }
            if (isset($trackData) && !empty($trackData))
            {
                foreach ($trackData as $k => $v)
                {
                    if ($v['eventName'] !== '')
                    {
                        // 批量打点
                        SensorsData::track($uid, true, $v['eventName'], $v['eventData']);
                    }
                }
            }
        }
        catch (Exception $e)
        {
            Log::write('打点失败 订单号：' . $order_id . ' ' . $e->getMessage() . ' [' . $e->getFile() . ':' . $e->getLine() . ']', 'error', true);
        }
    }

    /**
     * 获取订单打点通用数据
     * @param $sensorsTrackData array 打点数据
     * @param $order_id string 订单号
     * @param $res array
     * @param $event string 事件名称
     * @throws Exception
     */
    protected function getSensorsTrackCommonData(&$sensorsTrackData, $order_id, $res, $event): void
    {
        if (isset($res) && !empty($res))
        {
            if (isset($res['extend']) && $res['extend'])
            {
                $extend = json_decode($res['extend'], true);
                if (!empty($extend['coupon']))
                {
                    $res['is_use_coupon'] = 1;
                    $res['coupon_price'] = $extend['coupon']['discount_price'];
                    $cid = $extend['coupon']['cid'];
                    $coupon = (new UserCoupon())->getInfoById($cid, ['type', 'c_id']);
                    switch ($coupon['type'])
                    {
                        case 1: //若是折扣，直接扣除,
                            $cname = '折扣券';
                            break;
                        case 2://若是满减立减，则减去活动价格
                        case 3://若是满减立减，则减去活动价格
                            $cname = '满减券';
                            break;
                        case 4://随机券
                            $cname = '随机券';
                            break;
                        case 5://免费券
                            $cname = '免费券';
                            break;
                    }
                }
                if (!empty($extend['active']))
                {
                    $res['active_id'] = $extend['active']['ac_id'] ?? 0;
                    $res['active_name'] = $extend['active']['name'] ?? '';
                    $res['is_official_active'] = 1;
                    $res['active_discount'] = $extend['active']['discount_price'];
                } elseif (!empty($extend['new_active']))
                {
                    $acPrice = 0;
                    $acType = 0;
                    foreach ($extend['new_active'] as $ac)
                    {
                        if ($ac['type'] == 2)
                        {
                            $acType = 2;
                            $sensorsTrackData['is_live_active'] = true;
                        } elseif ($ac['type'] == 1)
                        {
                            $acType = 1;
                            $res['active_id'] = $ac['ac_id'];
                            $res['active_name'] = $ac['name'];
                            $res['is_official_active'] = 1;
                        }
                        $acPrice += $ac['discount_price'] * $ac['num'];
                    }
                    if ($acType == 1)
                    {
                        $res['active_discount'] = $acPrice;
                    } elseif ($acType == 2)
                    {
                        $sensorsTrackData['live_price'] = $acPrice;
                    }
                }
                if (isset($extend['live_info']))
                {
                    $sensorsTrackData['live_id'] = $extend['live_info']['live_id'] ?? 0;
                    $sensorsTrackData['live_record_id'] = $extend['live_info']['live_record_id'];
                }
            }
            $couponPrice = isset($res['coupon_price']) ? $res['coupon_price'] * 1 : 0;
            $activeDiscount = isset($res['active_discount']) ? $res['active_discount'] * 1 : 0;
            $totalDiscount = $activeDiscount + $couponPrice;
            if ($event !== 'WalletRechargeSuccess')
            {
                $sensorsTrackData['coupon_id'] = $coupon['c_id'] ?? 0;// 后台优惠券id
                $sensorsTrackData['is_use_coupon'] = isset($res['is_use_coupon']);// 是否使用优惠券
                $sensorsTrackData['coupon_type'] = $cname ?? '';// 优惠券类型
                $sensorsTrackData['coupon_price'] = $couponPrice;// 优惠金额
                $sensorsTrackData['active_id'] = $res['active_id'] ?? 0;// 官方活动id
                $sensorsTrackData['active_name'] = $res['active_name'] ?? '';// 官方活动名称
                $sensorsTrackData['is_official_active'] = isset($res['is_official_active']);// 是否有官方活动
                $sensorsTrackData['active_price'] = $activeDiscount;// 活动优惠金额
                $sensorsTrackData['total_discount'] = $totalDiscount;// 总优惠金额
            }

            $sensorsTrackData['total_amount'] = $res['total_amount'] * 1;// 实付价格
            $sensorsTrackData['order_id'] = $order_id;// 订单编号
            $sensorsTrackData['trade_type'] = (int)$res['trade_type'];// 支付方式
            // 只有支付成功时，有以下两个字段
            if (!strpos($event, 'Confirm'))
            {
                $sensorsTrackData['is_success'] = true;// 是否成功
                $sensorsTrackData['failed_reson'] = '';// 失败原因
            }
        }
    }

    /**
     * 获取档案订单编号
     * @param $uid
     * @param $rid
     * @param $order_type
     * @return array|false|mixed
     * @throws Exception
     */
    public function getRecodeOrderIds($uid, $rid, $order_type)
    {
        $ordersModel = new OrdersCacheModel();
        //获取当前档案购买的订单
        if ($order_type)
        {
            if ($order_type === 17)
            {
                $orderIds = (new ZlSynastryReport())->getRidSynastryReportOrderIds($uid, $rid);
            } elseif ($order_type === 15)
            {
                $orderIds = (new ZlcrCustomReportQuestion())->getRecodeQuestionOrderIds($uid, $rid);
            } else
            {
                $orderIds = $ordersModel->PrepaidUnpaidOrderIds($uid, $rid, $order_type, 1);
            }
        } else
        {
            $orderTypes = [1, 2, 3, 4, 5, 7];
            $tmpIds = [];
            foreach ($orderTypes as $type)
            {
                $tmpIds[] = $ordersModel->PrepaidUnpaidOrderIds($uid, $rid, $type, 1);
            }
            $orderIds1 = [];
            array_walk_recursive($tmpIds, static function ($value) use (&$orderIds1)
            {
                $orderIds1[] = $value;
            });

            $orderIds2 = (new ZlSynastryReport())->getRidSynastryReportOrderIds($uid, $rid);

            $orderIds3 = (new ZlcrCustomReportQuestion())->getRecodeQuestionOrderIds($uid, $rid);
            // 你的理想型
            $orderIds4 = (new Zl1RelationAnalysisFitYou())->getRecodeFitYouOrderIds($uid, $rid);
            // 怎么追求Ta 和 鉴"渣"申请
            $orderIds5 = (new Zl1RelationAnalysisReport())->getRecodeRelationAnalysisReportOrderIds($uid, $rid);

            $orderIds = array_merge($orderIds1, $orderIds2, $orderIds3, $orderIds4, $orderIds5);
        }
        return $orderIds;
    }
}
